class webNetworkMananger {

	public isConnecteed: boolean;
	public constructor() {

	}
	/**心跳 */
	private hertBeatTimer: egret.Timer;
	private static instance: webNetworkMananger;
	public static getInstance(): webNetworkMananger {
		if (this.instance == null) {
			this.instance = new webNetworkMananger();
		}
		return this.instance;
	}
	private heartTimer() {
		// this.hertBeatTimer = new egret.Timer(1000, -1);
		// this.hertBeatTimer.addEventListener(egret.TimerEvent.TIMER, e => {
		// 	if (this.isConnecteed == true)
		// 		webNetworkMananger.getInstance().SendMeesage('hert', {});
		// }, this);
		// this.hertBeatTimer.start();
	}

	//用来接受游戏场景的
	public gameSceneRec: any;

	public static test: boolean = false;
	public miao: number;
	public yimiaohowzhen: number;
	/**数据长度 */
	public dataLong: number;

	/**服务器移动 */
	private _root_url: string = "127.0.0.1";
	public static isServerMove: boolean = false;

	private webSocket: egret.WebSocket;

	//CONCNET SERVER
	public connect(): void {
		if (this._root_url === null || DataProl.gameaddr_ip == null || DataProl.gameaddr_port
			== null) {
			console.error("未设置连接HOST IP");
			return;


		}
		// if (this.isConnecteed === true) {
		// 	console.error("服务器已经连接");
		// 	let m_AwesomeMessage = new awesomepackage.AwesomeMessage();
		// 	let m_c2sEnterRoom = new awesomepackage.c2sEnterRoom();
		// 	m_c2sEnterRoom.account = DataProl.account;

		// 	m_c2sEnterRoom.deessUp = JSON.stringify(DataProl.userCurrentDressUp);

		// 	m_AwesomeMessage.meesageId = 1002;
		// 	m_AwesomeMessage.data = awesomepackage.c2sEnterRoom.encode(m_c2sEnterRoom).finish();

		// 	var buffer = awesomepackage.AwesomeMessage.encode(m_AwesomeMessage).finish();
		// 	var byte2: egret.ByteArray = new egret.ByteArray(buffer);
		// 	webNetworkMananger.getInstance().SendBitMeesage(byte2);

		// 	return;
		// }
		this.webSocket = new egret.WebSocket();
		//设置数据格式为二进制，默认为字符串
		this.webSocket.type = egret.WebSocket.TYPE_BINARY;
		//添加收到数据侦听，收到数据会调用此方法
		this.webSocket.addEventListener(egret.ProgressEvent.SOCKET_DATA, this.onReceiveMessage, this);
		//添加链接打开侦听，连接成功会调用此方法
		this.webSocket.addEventListener(egret.Event.CONNECT, this.onSocketOpen, this);
		//添加链接关闭侦听，手动关闭或者服务器关闭连接会调用此方法
		this.webSocket.addEventListener(egret.Event.CLOSE, this.onSocketClose, this);
		//添加异常侦听，出现异常会调用此方法
		this.webSocket.addEventListener(egret.IOErrorEvent.IO_ERROR, this.onSocketError, this);
		//console.log("gameip" + DataProl.gameaddr_ip + ":" + DataProl.gameaddr_port);
		//连接服务器
		//DataProl.gameaddr_ip="172.16.19.163";
		//DataProl.gameaddr_ip="172.16.17.7";
		//DataProl.gameaddr_port = '3011';
		//	DataProl.gameaddr_ip = "127.0.0.1";
		//	console.log("serverip:" + DataProl.gameaddr_ip + "serverport:" + DataProl.gameaddr_port);
		//this.webSocket.connect('140.143.211.89', 3111);
		this.webSocket.connectByUrl('wss://meiruiya12.cn');
		//this.webSocket.connect('172.16.19.104', 3111);
		//his.webSocket.connect('132.232.205.216', 3014);
		//this.webSocket.connect('172.16.18.54', 3111);
		//	this.webSocket.connect(DataProl.gameaddr_ip, DataProl.gameaddr_port);
	}

	public onSocketOpen(): void {
		this.isConnecteed = true;
		//DataProl.login_main_handle.test_invite();
		LoginMain.LoginBackMess = 0;
		//	console.log("连接成功");
	}

	public onSocketClose(): void {
		this.isConnecteed = false;
		LoginMain.LoginBackMess = 1;
		//	console.log("连接失败");
	}

	public onSocketError(): void {
		//console.log("连接报错");

	}

	public SendBitMeesage(mes: egret.ByteArray): void {
		this.webSocket.writeBytes(mes);
		this.webSocket.flush();
	}
	//send message
	// public SendMeesage(type: string, mes: any): void {

	// 	var msg = {
	// 		"cmdName": type,
	// 		"data": mes
	// 	}
	// 	//	var deflate = new Zlib.Deflate("123");
	// 	// var compressed = deflate.compress();
	// 	// this.webSocket.writeUTF(JSON.stringify(msg));

	// 	// var byte: egret.ByteArray = new egret.ByteArray();
	// 	// //byte.writeUTF(JSON.stringify(msg));
	// 	// byte.writeUTF("1231");
	// 	// byte.position = 0;
	// 	// this.webSocket.writeBytes(byte, 0, byte.bytesAvailable);
	// 	// this.webSocket.flush();
	// 	// var byte: egret.ByteArray = new egret.ByteArray();
	// 	// var stt = JSON.stringify(msg);
	// 	// byte.writeUTFBytes(JSON.stringify(msg));
	// 	//  console.log("压缩前大小"+byte.length)
	// 	//  var tt = JSZip.compressions.DEFLATE.compress(	byte.bytes	, { level: 9 });;
	// 	//   console.log("压缩后大小"+tt.length);
	// 	//   	var byte2: egret.ByteArray = new egret.ByteArray(tt);
	// 	let ptest = new awesomepackage.AwesomeMessage();
	// 	//	ptest.awesomeField = "tt";
	// 	console.log(ptest);
	// 	var buffer = awesomepackage.AwesomeMessage.encode(ptest).finish();
	// 	var byte2: egret.ByteArray = new egret.ByteArray(buffer);
	// 	this.webSocket.writeBytes(byte2);
	// 	this.webSocket.flush();

	// }

	//recive message
	public onReceiveMessage(e: egret.Event): void {
		var byte: egret.ByteArray = new egret.ByteArray();
		this.webSocket.readBytes(byte);

		//	var msg = byte.readUTFBytes(byte.bytes);

		// var boo:boolean = byte.readBoolean();
		// var num:number = byte.readInt();
		//	var msg = this.webSocket.readUTF();
		//	this.reciveMessageHandle(JSON.parse(byte));
		//	var msg = this.webSocket.Bytes();
		//	var obj = JSON.parse(msg);
		//	var obj2 = JSON.parse(obj);

		this.reciveMessageHandle(byte.bytes);
	}
	//import { YIM, YIMErrorcode, getInstance, IEventObject, MessageBodyType, MessageVoiceType } from "yim";
	/**显示错误信息 */
	public showErrorMessage(data: any) {
		console.log(data);
		//this.gameSceneRec.displayErrorMessage(data);
	}

	public LoginGameServer() {
		let userinfo = weixinManager.getInstance().getUserInfo();
		let headUrl;
		let sex;
		if (userinfo != null && userinfo != undefined) {
			headUrl = weixinManager.getInstance().getUserInfo().avatarUrl;
			if (headUrl == null || headUrl == undefined) {
				headUrl = "text";
			}
			sex = weixinManager.getInstance().getUserInfo().gender;
			if (sex == null || sex == undefined) {
				sex = true;
			} else if (sex == 1) {
				sex = true;
			} else {
				sex = false;
			}
		} else {
			headUrl = "text";
			sex = true;
		}
		let m_AwesomeMessage = new awesomepackage.AwesomeMessage();
		let m_c2sLogin = new awesomepackage.c2sLogin();
		m_c2sLogin.account = DataProl.account;
		m_c2sLogin.sign = DataProl.sign;
		m_c2sLogin.nickname = gameGlobal.global.playerName;
		m_c2sLogin.headUrl = headUrl;
		m_c2sLogin.sex = sex;
		m_c2sLogin.deessUp = JSON.stringify(DataProl.userCurrentDressUp);
		m_AwesomeMessage.meesageId = 1001;
		m_AwesomeMessage.data = awesomepackage.c2sLogin.encode(m_c2sLogin).finish();
		var buffer = awesomepackage.AwesomeMessage.encode(m_AwesomeMessage).finish();
		// plain = Array.<number> or Uint8Array
		//var deflate = new Zlib.Deflate(buffer);
		//var compressed = deflate.compress();

		// // compressed = Array.<number> or Uint8Array
		// var inflate = new Zlib.Inflate(compressed);
		// var plain = inflate.decompress();


		var byte2: egret.ByteArray = new egret.ByteArray(buffer);
		// var pMessaage = awesomepackage.AwesomeMessage.decode(byte2);
		// var tmpMessage =awesomepackage.c2sLogin.decode(pMessaage.data);


		webNetworkMananger.getInstance().SendBitMeesage(byte2);
	}
	/**进入好友模式等待房间 */
	public intoFriendWaitRoom() {
		let m_AwesomeMessage = new awesomepackage.AwesomeMessage();
		let m_c2sEnterInvoteRoom = new awesomepackage.c2sEnterInvoteRoom();
		m_c2sEnterInvoteRoom.account = DataProl.account;
		DataProl.waitRoomId = DataProl.waitRoomId;
		//-----------------------------------测试好友模式直接输房间号
		m_c2sEnterInvoteRoom.waitRoomId = DataProl.waitRoomId;
		m_AwesomeMessage.meesageId = 2001;
		m_AwesomeMessage.data = awesomepackage.c2sEnterInvoteRoom.encode(m_c2sEnterInvoteRoom).finish();
		var buffer = awesomepackage.AwesomeMessage.encode(m_AwesomeMessage).finish();
		var byte2: egret.ByteArray = new egret.ByteArray(buffer);
		webNetworkMananger.getInstance().SendBitMeesage(byte2);
	}
	/**进入房间1002 */
	public intoRoom() {
		let m_AwesomeMessage = new awesomepackage.AwesomeMessage();
		let m_c2sEnterRoom = new awesomepackage.c2sEnterRoom();
		m_c2sEnterRoom.account = DataProl.account;
		m_c2sEnterRoom.waitRoomId = DataProl.waitRoomId;
		m_AwesomeMessage.meesageId = 1002;
		m_AwesomeMessage.data = awesomepackage.c2sEnterRoom.encode(m_c2sEnterRoom).finish();
		var buffer = awesomepackage.AwesomeMessage.encode(m_AwesomeMessage).finish();
		var byte2: egret.ByteArray = new egret.ByteArray(buffer);
		webNetworkMananger.getInstance().SendBitMeesage(byte2);
	}
	public reciveMessageHandle(backData: any) {

		var pMessaage = awesomepackage.AwesomeMessage.decode(backData);
		//console.log("接受消息:" + pMessaage.meesageId);
		//this.showSecondFrames(pMessaage.data.length);
		if (pMessaage.meesageId == 1000) {
			this.LoginGameServer();
		}
		//登陆成功
		if (pMessaage.meesageId == 1101) {
			DataProl.isEvenOnNet = true;
			if (DataProl.login_main_handle != null) {
				DataProl.login_main_handle.showNetMode();
				DataProl.login_main_handle.getLaunchInfo();
				//DataProl.login_main_handle.test_invite();
			}

		}
		if (pMessaage.meesageId == 1102) {
			let tmpMessage = awesomepackage.s2cEnterRoom.decode(pMessaage.data);
			var screenDate = {
				"screenWidth": 2500,//gameMap.getInstance().canvas_Width,
				"screenHeight": 2500,//gameMap.getInstance().canvas_Height
			}
			if (tmpMessage.roomId == 0) {
				console.log("进入房间已满");
				DataProl.login_main_handle.show_reconnection_Main();
				return;
			}
			DataProl.roomid = tmpMessage.roomId;
			//	webNetworkMananger.getInstance().SendMeesage('windowResized', screenDate);
			DataProl.roomStartTime = 0;
			DataProl.roomTime = tmpMessage.roomStartTime;
			SceneManager.instance.SitchScene(SceneName.联网场景);
			if (this.gameSceneRec != null)
				this.gameSceneRec.playerPanel.showRoomId();
			if (DataProl.login_main_handle.invitationMain && DataProl.loginType != 0) {
				DataProl.login_main_handle.invitationMain.dissolvedRoom();
			}
			return;
		}
		if (pMessaage.meesageId == 1103) {
			if (this.miao == null) {
				this.miao = new Date().getSeconds();
				this.yimiaohowzhen = 0;
			}
			if (this.miao == new Date().getSeconds()) {
				this.yimiaohowzhen++;
			} else {
				this.miao = new Date().getSeconds();
				//console.log(this.yimiaohowzhen);
				DataProl.frameNumber = this.yimiaohowzhen;
				this.yimiaohowzhen = 0;
			}

			gameGlobal.global.gameStart = true;
			gameGlobal.global.died = false;

			var databuffer = new Zlib.Inflate(new Uint8Array(pMessaage.data));
			var bufferdata = databuffer.decompress();
			var transfromData = awesomepackage.s2cPlayerMove.decode(bufferdata);//this.transfromData(backData.data.userData);
			//		var userDataT=awesomepackage.roomPlayerInfo.decode(transfromData.userData);
			var translatedLineData = this.transfromLineData(transfromData.lineData);
			var useData = {
				"userData": transfromData.userData,
				"lineList": translatedLineData,
				"timeStamp": Date.now()
			};

			if (this.gameSceneRec != null) {
				this.gameSceneRec.handleInformationByServer(useData);
			}
			else {
				console.log("this.gameSceneRec==null");
			}

			return;
		}

		if (pMessaage.meesageId == 1106) {
			var tt = awesomepackage.s2cRespawn.decode(pMessaage.data);
			// if (tt.isRebirth == 0) {
			// 	webNetworkMananger.getInstance().gameSceneRec.isUserDied = false;
			// 	return;
			// }
			DataProl.roomStartTime = 0;
			DataProl.roomTime = tt.startRoomTime;

			if (this.gameSceneRec != null)
				this.gameSceneRec.playerPanel.startRoomTimer();
		}
		//处理排行榜信息
		if (pMessaage.meesageId == 1107) {
			var tl = awesomepackage.s2cTopList.decode(pMessaage.data);
			// if (this.gameSceneRec != null)
			// 	this.gameSceneRec.playerPanel.showNetTop(tl.tops, tl.min);
		}
		//游戏结束
		if (pMessaage.meesageId == 1108) {
			if (this.gameSceneRec != null) {
				var tgo = awesomepackage.s2cGameOver.decode(pMessaage.data);
				this.gameSceneRec.gameOverDis(tgo.roomUser);
			}
		}
		//处理道具
		if (pMessaage.meesageId == 1109) {
			var ttporp = awesomepackage.s2cAllPorp.decode(pMessaage.data);
			if (ttporp != null && ttporp != undefined) {
				DataProl.allPropData = ttporp.propData;
				//this.gameSceneRec.m_propMg.propsUpdata(ttporp.propData);
			}
		}
		//-------------------------------------------------------------好友模式
		//进入好友模式成功
		if (pMessaage.meesageId == 2101) {
			let tmpMessage = awesomepackage.s2cEnterInvoteRoomSuc.decode(pMessaage.data);
			DataProl.waitRoomId = tmpMessage.waitRoomId;
			console.log("房间号为" + DataProl.waitRoomId);
			switch (DataProl.waitRoomId) {
				case -1:
					//房间已满
					console.log("房间已满");
					break;
				case -2:
					//创建房间失败
					console.log("创建房间失败");
					break;
				case -3:
					//获取信息失败
					console.log("获取信息失败");
					break;
				case -4:
					//发送玩家信息失败
					console.log("发送玩家信息失败");
					break;

				default:
					if (DataProl.login_main_handle) {
						DataProl.login_main_handle.showFriendMain();
						console.log("即将进入邀请好友模式");
						let m_AwesomeMessage = new awesomepackage.AwesomeMessage();
						let m_c2SInvoteRoomInfo = new awesomepackage.c2sEnterInvoteRoom();
						m_c2SInvoteRoomInfo.account = DataProl.account;
						m_c2SInvoteRoomInfo.waitRoomId = DataProl.waitRoomId;
						m_AwesomeMessage.meesageId = 2002;
						m_AwesomeMessage.data = awesomepackage.c2SInvoteRoomInfo.encode(m_c2SInvoteRoomInfo).finish();
						var buffer = awesomepackage.AwesomeMessage.encode(m_AwesomeMessage).finish();
						var byte2: egret.ByteArray = new egret.ByteArray(buffer);
						webNetworkMananger.getInstance().SendBitMeesage(byte2);
					}
					break;
			}

		}

		//匹配成功，接受广播消息
		if (pMessaage.meesageId == 2102) {
			let tmpMessage = awesomepackage.s2cInvoteRoomInfo.decode(pMessaage.data);
			DataProl.waitRoomId = tmpMessage.waitRoomId;
			if (DataProl.login_main_handle) {
				/**如果只有自己的话 */
				if (tmpMessage.players.length == 1) {
					DataProl.login_main_handle.invitationMain.clearUserMsg();
					return;
				} else if (tmpMessage.players.length == 2) {
					DataProl.login_main_handle.invitationMain.CanStartGame();
				}
				for (let i = 0; i < tmpMessage.players.length; i++) {
					if (tmpMessage.players[i].nickname != gameGlobal.global.playerName) {
						DataProl.login_main_handle.invitationMain.ShowMsg({
							name: tmpMessage.players[i].nickname,
							headUrl: tmpMessage.players[i].headUrl,
							sex: tmpMessage.players[i].sex
						});
						return;
					}
				}
			}
		}
		//退出房间成功
		if (pMessaage.meesageId == 2104) {
			let tmpMessage = awesomepackage.s2cRoomExit.decode(pMessaage.data);
			if (DataProl.login_main_handle) {
				DataProl.login_main_handle.invitationMain.dissolvedRoom(tmpMessage.result);
			}
		}
		//吐舌消息
		if (pMessaage.meesageId == 1130) {
			let tmpMessage = awesomepackage.s2cShoot.decode(pMessaage.data);
			this.gameSceneRec.dellPlayerShoot(tmpMessage);
		}
		//断线反作用力
		if (pMessaage.meesageId == 1131) {
			let tmpMessage = awesomepackage.s2cShoot.decode(pMessaage.data);
			this.gameSceneRec.disposeCounterforce(tmpMessage);
		}
		/**提示错误信息 */
		if (pMessaage.meesageId == 300) {
			var terr = awesomepackage.s2cErroMessage.decode(pMessaage.data);
			if (this.gameSceneRec != null)
				this.showErrorMessage(terr);
		}


		// if (backData.cmdName == "gameMapInit") {
		// 	if (this.gameSceneRec != null)
		// 		this.gameSceneRec.mapElementInit(backData.data);
		// }





	}
	/**显示每秒帧数 */
	showSecondFrames(dataLong) {
		if (this.miao == null) {
			this.miao = new Date().getSeconds();
			this.dataLong = 0;
		}
		if (this.miao == new Date().getSeconds()) {
			this.dataLong += dataLong;
		} else {
			this.miao = new Date().getSeconds();
			//console.log("数据长度:" + this.dataLong);
			this.dataLong = 0;
		}
	}

	/**转换数据  /玩家/ */
	private transfromData(userData) {
		var data = [];
		for (var t = 0; t < userData.length; t++) {
			data.push(this.transfromUserData(userData[t]));
		}
		return data;
	}
	/**转换一个玩家的数据 */
	private transfromUserData(usss) {
		var currentPlayer = {
			name: usss.na,
			userId: usss.us,
			x: usss.x,
			y: usss.y,
			type: usss.ty,
			frogType: usss.fTy,
			level: usss.le,
			lineLength: usss.lLe,
			roomId: usss.rId,
			ishadLine: usss.isL,
			disconnection_line: false,
			disconnection_line_time: -1,
			propStates: usss.propStates,
			death:
			{
				isDeath: usss.dh.Dh,
				deadStartTime: usss.dh.dST
			},
			NewHandProtect:
			{
				isProtect: usss.NP.iP,
				ProtectStartTime: usss.NP.PST,

			},
			dressup: {
				decorateId: usss.dp.dI,
				trailingId: usss.dp.tI
			}
		};
		return currentPlayer;
	}
	/**转换线数据 */
	private transfromLineData(lineData) {
		var data = [];
		for (var t = 0; t < lineData.length; t++) {
			data.push(this.transfromLine(lineData[t]));
		}
		return data;
	}
	//转换单个线的数据
	private transfromLine(line) {
		var curLine = {
			uop: line.uO,
			utp: line.uT,
			userOneId: line.uOI,
			userTwoId: line.uTI,
			type: line.t
		};
		return curLine;
	}
}